<template>
  <el-container>
    <el-main class="popup_content">
      <el-form ref="editPromotion" :model="editPromotion" :rules="rules" label-width="90px">
        <el-form-item label="活动商品" prop="goodsId" style="width:520px">
          <product-choose :data="productsName" @chooseProduct="chooseProduct"></product-choose>
          <!-- <el-select v-model="productsName" clearable style="width: 100%" value-key="goodsId" @change="productsChange"
            placeholder="请选择商品" filterable :filter-method="getProductList">
            <el-option v-for="item in productOptions" :label="item.name" :value="item" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="活动描述" prop="title" style="width:520px">
          <el-input v-model="editPromotion.title" placeholder="如消费满100元生效"></el-input>
        </el-form-item>
        <el-form-item label="起止日期" prop="dateTime" style="width:520px">
          <el-date-picker v-model="editPromotion.dateTime" style="width:100%" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赠品类型" style="width:250px;" prop="giftType">
          <el-select style="width: 100%;" v-model="editPromotion.giftType" placeholder="请选择" @change="giftChoose">
            <el-option v-for="item in giftTypeForm" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width:520px;" label="优惠券名称" v-if="editPromotion.giftType == 1">
          <el-select style="display: inline-block;width: 100%;" v-model="editPromotion.gifts[0].giftName" value-key="id" placeholder="请选择优惠券" @change="couponClick">
            <el-option v-for="(item,index) in couponForm" :key="item.id" :label="item.name" :value="item" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width:520px;" :label="editPromotion.giftType == 1?'优惠券数量':editPromotion.giftType == 3?'购物券数量':'兑换券数量'">
          <el-input v-model="editPromotion.gifts[0].quantity" placeholder="请输入赠品数量"></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="活动库存" prop="stock" style="width:250px">
            <el-input type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent
              v-model="editPromotion.stock" placeholder="请输入库存"></el-input>
          </el-form-item>
          <div style="display: flex;align-items: center;flex: 1;margin-bottom: 20px;margin-left: 20px;">
            <el-checkbox v-model="editPromotion.firsted">只适用于首单生效</el-checkbox>
          </div>
        </div>
        <div>
          <el-form-item label="参与会员" style="width: 520px">
            <el-select style="width:100%;" v-model="vipsvalue" multiple filterable allow-create default-first-optionplaceholder="请选择可参与会员"
              @change="vipschanges">
              <el-option v-for="item in vipslist" :key="item.id" :label="item.name" :value="item.vip"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="参与城市" style="width: 520px">
            <queryCascader style="width:100%;" @queryCascaderclick=queryCascaderclick :areaList='editPromotion.areaList'></queryCascader>
          </el-form-item>
        </div>

        <el-form-item>
          <el-col :span="12">
            <el-button type="primary" :loading="clicked" @click="updatePromotion('editPromotion')">确 定</el-button>
          </el-col>
        </el-form-item>
      </el-form>

    </el-main>
  </el-container>
</template>

<script>
  import queryCascader from '@/components/Query/queryCascader'
  import editCoupon from '@/views/promotion/components/editCoupon'
  import {
    EventBus
  } from '@/api/eventBus'
  import {
    find,
    update
  } from '@/api/promotion'
  import {
    list as productList
  } from '@/api/product'
  import {
    list
  } from '@/api/vip'
  import { list as couponList } from '@/api/coupon'
  import utils from '@/utils/utils'
  import productChoose from "../components/product.vue"
  export default {
    name: 'buyzeng-edit',
    data() {
      return {
        vipsvalue: [],
        vipslist: [],
        products: [],
        clicked: false,
        giftTypeList: [],
        productOptions: [],
        productsName: '',
        editPromotion: {
          dateTime: [],
          id: '',
          givenAmount: 0,
          agioRate: 0,
          amount: 0,
          firsted: false,
          goodsId: '',
          giftType: '',
          gifts: [{
            promotionId: '',
            giftId: '',
            availableQuantity: 0,
            giftName: '',
            quantity: 0
          }],
          introduction: '',
          minimumPrice: 0,
          modifyDate: '',
          orders: 0,
          stock: 0,
          overlying: false,
          thumbnail: '',
          title: '',
          type: 11,
          vips: '',
          areaList: ''
        },
        rules: {
          type: [{
            required: true,
            message: '请输入选择类型',
            trigger: 'change'
          }, ],
          agioRate: [{
            required: true,
            message: '请输入满减比例',
            trigger: 'blur'
          }, ],
          amount: [{
            required: true,
            message: '请输入金额',
            trigger: 'blur'
          }, ],
          giftType: [{
            required: true,
            message: '请选择类型',
            trigger: 'blur'
          }, ],
          goodsId: [{
            required: true,
            message: '请选择促销商品',
            trigger: 'change'
          }, ],
          quantity: [{
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }, ],
          minimumPrice: [{
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }, ],
          dateTime: [{
            required: true,
            message: '请输入活动日期',
            trigger: 'change'
          }, ],
          integer: [{
            required: true,
            message: '请输入优先级',
            trigger: 'blur'
          }, ],
          introduction: [{
            required: true,
            message: '请输入促销说明',
            trigger: 'blur'
          }, ],
        },
        giftTypeForm:[{
          value: '1',
          label: '优惠券'
        }, {
          value: '2',
          label: '兑换券'
        }, {
          value: '3',
          label: '购物券'
        }],
        couponForm:[]
      }
    },
    components: {
      editCoupon,
      queryCascader,
      productChoose
    },
    watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
      $route(newVal, oldVal) {
        console.log(newVal);
        if (newVal.name == 'buyzeng-edit' && newVal.query.id != this.id) {
          this.findPromotion()
        }
      }
    },
    methods: {
      queryCascaderclick(data) {
        this.editPromotion.areaList = data
      },
      vipschanges(val) {
        this.editPromotion.vips = ''
        val.forEach(item => {
          this.editPromotion.vips += item
        })
      },
      loadVip() {
        list().then(res => {
          console.log(res);
          this.vipslist = res.data.data
        })
      },
      loadCommodity() {
        productList().then(response => {
          response.data.data.forEach(item => {
            let product = {
              name: item.name,
              id: item.id,
              goodsId: item.goodsId
            }
            this.products.push(product)
          })

        })
      },
      addCoupon() {
        this.$refs.editCouponAdd.add()
      },
      findPromotion() {
        var _this = this
        this.editPromotion.id = this.$route.query.id;
        find(this.editPromotion.id).then(response => {
          response.data.promotion.dateTime = []
          response.data.promotion.dateTime.push(response.data.promotion.beginDate)
          response.data.promotion.dateTime.push(response.data.promotion.endDate)
          this.editPromotion = response.data.promotion;
          if(utils.isNull(response.data.promotion.gifts)){
            console.log('我进来了')
            _this.editPromotion.gifts = [{
              promotionId: '',
              giftId: '',
              availableQuantity: 0,
              giftName: '',
              quantity: 0
            }]
          }
          console.log(this.editPromotion)
          console.log('数据')
          this.editPromotion.giftType = this.editPromotion.giftType.toString()
          this.productsName = response.data.promotion.productName;
          console.log(this.editPromotion)
          this.vipsvalue = this.editPromotion.vips.split('')
          let array = []
          this.vipsvalue.forEach(item => {
            array.push(Number(item))
          })
          this.vipsvalue = array
        })
      },
      getProductList(query) { // 加载商品
        productList({
          keyword: query,
          pageSize: 20,
          isList: true
        }).then(res => {
          this.$set(this.$data, 'productOptions', res.data.data)
        }).catch(err => {
          console.log(err)
        })
      },
      updatePromotion(editPromotion) {
        if (this.editPromotion.giftType=="1") {
          if(!this.editPromotion.gifts[0].giftId){
            this.$message.error('请选择优惠券');
            return
          }
        }
        if(!this.editPromotion.gifts[0].quantity){
          this.$message.error('请输入赠品数量');
          return
        }
        this.$refs[editPromotion].validate((valid) => {
          if (valid) {
            this.clicked = true
            var editPromotion = {
              id: this.editPromotion.id,
              agioRate: this.editPromotion.agioRate,
              amount: this.editPromotion.amount,
              firsted: this.editPromotion.firsted,
              giftType: this.editPromotion.giftType,
              gifts: this.editPromotion.gifts,
              beginDate: '',
              endDate: '',
              status: 0,
              goodsId: this.editPromotion.goodsId,
              introduction: this.editPromotion.introduction,
              minimumPrice: this.editPromotion.minimumPrice,
              modifyDate: new Date(),
              orders: this.editPromotion.orders,
              overlying: this.editPromotion.overlying,
              thumbnail: this.editPromotion.thumbnail,
              title: this.editPromotion.title,
              type: this.editPromotion.type,
              stock: this.editPromotion.stock,
              vips: this.editPromotion.vips,
              areaList: this.editPromotion.areaList,
            }
            if (this.editPromotion.dateTime.length > 0) {
              editPromotion.beginDate = this.editPromotion.dateTime[0];
              editPromotion.endDate = this.editPromotion.dateTime[1]
            }
            update(editPromotion).then(response => {
              this.$store.dispatch('tagsView/delView', this.$route).then(({
                visitedViews
              }) => {
                this.$router.push({
                  path: '/buyzeng/list'
                })
              })
              this.clicked = false
              EventBus.$emit('buyzeng-edit', response.data)
            }).catch(error => {
              this.clicked = false
              console.log('error')
            })
          }
        })
      },
      chooseProduct(data){
            console.log('1121212')
            this.editPromotion.goodsId = data.goodsId;
            this.productName = data.name;
      },
      productsChange(val) {
        console.log(val)
        this.editPromotion.goodsId = val.goodsId
      },
      // 优惠券
      couponList(){
        var _this = this
        couponList().then(response =>{
          _this.couponForm = response.data.data
        })
      },
      //优惠券选择
      couponClick(data){
        console.log(data)
        this.editPromotion.gifts[0].giftId = data.id
        this.editPromotion.gifts[0].giftName = data.name
      },
      // 赠品选择
      giftChoose(data){
        if(data == 3){
          this.editPromotion.giftType = "3"
          this.editPromotion.gifts[0].giftId = '0'
          this.editPromotion.gifts[0].giftName = '送购物券'
          this.editPromotion.gifts[0].quantity = 0
        }else if(data == 2){
          this.editPromotion.giftType = "2"
          this.editPromotion.gifts[0].giftId = '0'
          this.editPromotion.gifts[0].giftName = '兑换券'
          this.editPromotion.gifts[0].quantity = 0
        }else{
          this.editPromotion.giftType = "1"
          this.editPromotion.gifts[0].giftId = ''
          this.editPromotion.gifts[0].giftName = ''
          this.editPromotion.gifts[0].quantity = 0
        }
      }
    },
    created() {
      this.loadVip()
      this.findPromotion()
      this.getProductList('')
      this.couponList()
    },
    filters: {
      watchType(val) {
        if (val === 7) {
          return '买送'
        } else if (val === 8) {
          return '秒杀'
        } else if (val === 9) {
          return '第二件半价'
        } else if (val === 10) {
          return '新人价'
        } else if (val === 11) {
          return '买赠'
        }
      },
      watchMinimumPrice(val) {
        if (val == 7) {
          return '购买数量'
        }
      },
      watchlabeltype(val) {
        if (val === 7) {
          return '赠送数量'
        } else if (val === 8) {
          return '秒杀价格'
        } else if (val === 10) {
          return '新人价'
        }
      }
    }
  }
</script>

<style scoped>

</style>
